//
//  FreightAreaViewController.m
//  nonghubao
//
//  Created by Fenrir on 13-8-24.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "FreightAreaViewController.h"
#import "Helper.h"
#import "Config.h"

//  -业务逻辑细节说明-
//
//  @abstract       展示一个用户指定区域的运费模板。可以添加或修改区域和修改运费。在整个物流模板流程中主要起一个传递数据的介质的作用。

//  @discussion     如果是新增一个区域运费的话，向服务器发送的json数据在会在这个类里面组装（大概位置在line:117）。
//

//  @notes


//  -类修改日志-
//  修改人   修改时间   针对版本   修改描述

@interface FreightAreaViewController ()

@end

@implementation FreightAreaViewController
@synthesize unit = _unit;
@synthesize areaInfo = _areaInfo;
@synthesize delegate = _delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        _areasSelected = [NSMutableArray new];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    self.title = _L(@"vc_title_088");
    
    //返回按钮
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    //保存
    UIButton *saveButton = [Helper buttonWithStyle:ButtonStyleNavigationSave];
    [saveButton addTarget:self action:@selector(saveButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    NSString* filePath = [[NSBundle mainBundle] pathForResource:@"freight_area_unit" ofType:@"html"];
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT-44.0f)];
    _webView.delegate = self;
    //    _webView.scrollView.bounces = NO;
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
    [self.view addSubview:_webView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 事件

- (void)backButtonEvent:(id)sender
{
    
    //默认数量
    NSString *defaultQuantity = [_webView stringByEvaluatingJavaScriptFromString:@"default_quantity.value"];
    
    //默认金额
    NSString *defaultAmount = [_webView stringByEvaluatingJavaScriptFromString:@"default_amount.value"];
    
    //超出数量
    NSString *exceedQuantity = [_webView stringByEvaluatingJavaScriptFromString:@"exceed_quantity.value"];
    
    //超出金额
    NSString *exceedAmount = [_webView stringByEvaluatingJavaScriptFromString:@"exceed_amount.value"];
    
    if (_areaInfo == nil) {
        
        if (_areasSelected.count ==0 &&
            [defaultQuantity isEqualToString:@""] &&
            [defaultAmount  isEqualToString:@""] &&
            [exceedQuantity  isEqualToString:@""] &&
            [exceedAmount  isEqualToString:@""]
            )
        {
            [self.navigationController dismissModalViewControllerAnimated:YES];
        }
        else {
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_120") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
            alertView.tag = 1;
            [alertView show];
        }
        
        
    }
    else {
        if ([_areasSelected isEqualToArray:_areaInfo[@"areaFreightRegionList"]]
            && [defaultQuantity doubleValue]    == [_areaInfo[@"defaultQuantity"] doubleValue]
            && [defaultAmount doubleValue]      == [_areaInfo[@"defaultAmount"] doubleValue]
            && [exceedQuantity doubleValue]     == [_areaInfo[@"exceedQuantity"] doubleValue]
            && [exceedAmount doubleValue]       == [_areaInfo[@"exceedAmount"] doubleValue])
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
        else {
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_121") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
            alertView.tag = 2;
            [alertView show];
        }
    }
}

- (void)saveButtonEvent:(id)sender
{
    //默认数量
    NSString *defaultQuantity = [_webView stringByEvaluatingJavaScriptFromString:@"default_quantity.value"];
    
    //默认金额
    NSString *defaultAmount = [_webView stringByEvaluatingJavaScriptFromString:@"default_amount.value"];
    
    //超出数量
    NSString *exceedQuantity = [_webView stringByEvaluatingJavaScriptFromString:@"exceed_quantity.value"];
    
    //超出金额
    NSString *exceedAmount = [_webView stringByEvaluatingJavaScriptFromString:@"exceed_amount.value"];
    
    if (_areasSelected.count != 0) {
        
        //调用JS的tester方法，返回假就说明有字段没有被认证通过
        NSString* tester = [_webView stringByEvaluatingJavaScriptFromString:@"tester();"];
        BOOL result = [tester boolValue];
        
        //有没有通过认证的字段，就什么都不做
        if (result == false) {

            return;
        }
        
        //组合一个区域运费对象
        NSDictionary *freightAreaInfo = [NSDictionary dictionaryWithObjectsAndKeys:defaultQuantity,@"defaultQuantity",defaultAmount,@"defaultAmount",exceedQuantity,@"exceedQuantity",exceedAmount,@"exceedAmount",_areasSelected,@"areaFreightRegionList", nil];
        
        if ([defaultQuantity integerValue] <= 0 ||
            [defaultAmount integerValue] <= 0 ||
            [exceedQuantity integerValue] <= 0 ||
            [exceedAmount integerValue] <= 0
            )
        {
            [Helper showAlertWithTitle:@"" andMessage:_L(@"alert_112")];
            return;
        }
        
        //_areaInfo为空，表示新增一个区域运费模板；否则为修改
        if (_areaInfo == nil) {
            
            if ([_delegate respondsToSelector:@selector(freightAreaDidSelected:withType:)]) {
                
                [_delegate freightAreaDidSelected:freightAreaInfo withType:0];
            }
            
            [self.navigationController dismissModalViewControllerAnimated:YES];
        }
        else {
            
            if ([_delegate respondsToSelector:@selector(freightAreaDidSelected:withType:)]) {
                
                [_delegate freightAreaDidSelected:freightAreaInfo withType:1];
            }
            
            [self.navigationController popViewControllerAnimated:YES];
        }
        
    }
    else {
        [Helper showAlertWithTitle:@"" andMessage:_L(@"alert_108")];
        return;
    }
    
}

#pragma mark - 私有方法

//遍历所有的一级城市，并将他们显示出来
- (void)showAllCities:(NSMutableArray *)cities
{
    [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"area_list.innerHTML = '%@'", @""]];
    
    for (int i=0; i<cities.count; i++) {
        
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"area_list.innerHTML += '%@'", cities[i][@"province"]]];
        
        if (i != cities.count-1) {
            
            [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"area_list.innerHTML += '%@'", @","]];
        }
    }
}

#pragma mark - UIWebView Delegate

- (void)webViewDidFinishLoad:(UIWebView *)webView
{

    if (_areaInfo != nil) {
        
        [_areasSelected addObjectsFromArray:_areaInfo[@"areaFreightRegionList"]];
        
        [self showAllCities:_areaInfo[@"areaFreightRegionList"]];
        
        //默认数量
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"default_quantity.value=%@",_areaInfo[@"defaultQuantity"]]];
        
        //默认金额
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"default_amount.value=%@",_areaInfo[@"defaultAmount"]]];
        
        //超出数量
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"exceed_quantity.value=%@",_areaInfo[@"exceedQuantity"]]];
        
        //超出金额
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"exceed_amount.value=%@",_areaInfo[@"exceedAmount"]]];
        
        //不为空 显示出删除按钮
        
        [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"delete_button\").style.display = 'block';"];
    }
    else {
        [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"delete_button\").style.display = 'none';"];
    }
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSArray *strArray = [[request.URL.relativeString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]componentsSeparatedByString:@"?"];
    
    //选择区域
    if ([strArray[0] isEqualToString:@"open:area_select_vc"]) {
        
        AreaSelectViewController *areaSelectVC = [[AreaSelectViewController alloc] init];
        areaSelectVC.delegate = self;
        
        areaSelectVC.areaFreightRegionArray = _areasSelected;
        
        [self.navigationController pushViewController:areaSelectVC animated:YES];
        
    }
    
    //删除模板
    else if ([strArray[0] isEqualToString:@"delete:freight"]) {
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_111") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
        alertView.tag = 3;
        [alertView show];
    }
    
    //警告框
    else if ([strArray[0] isEqualToString:@"open:alert"]) {
        
        UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"" message:strArray[1] delegate:self cancelButtonTitle:_L(@"btn_yes_01") otherButtonTitles:nil];
        alerView.tag = 100;
        [alerView show];
    }
    
    return YES;
}

#pragma mark - AreaSelectedDelegate

- (void)areaSelected:(NSMutableArray *)areas
{
    if (_areasSelected.count != 0) {
        [_areasSelected removeAllObjects];
    }
    
    [_areasSelected addObjectsFromArray:areas];
    
//    NSLog(@"区域运费%@",_areasSelected);
    
    [self showAllCities:areas];
}

#pragma mark - UIAlerView Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1) {
        if (buttonIndex == 1) {
            
            [self.navigationController dismissModalViewControllerAnimated:YES];
        }
    }
    else if (alertView.tag == 2) {
        if (buttonIndex == 1) {
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else if (alertView.tag == 3) {
        if (buttonIndex == 1) {
            
            //要退出时，设定不在接受HTML的Alert
            _noAlert = true;
            
            if ([_delegate respondsToSelector:@selector(freightWillDelete)]) {
                [_delegate freightWillDelete];
                
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
    }
    else {
        
    }

}


@end

